<?php

    session_start();

    $error = 0;
    $errormessage = '';
    if (isset($_GET['error'])) {
        $error = $_GET['error'];
    }
    if ($error != '0') {
        $error = 1;
        $errormessage = 'test error message';
    }

    $_SESSION['user_id'] = '';
    $login['logged'] = false;

    $email = trim($_GET['email']);
    $password = trim($_GET['password']);
    $nickname = trim($_GET['nickname']);
    $mdPassword = md5($password.'if039');

    if (!(empty($email) || empty($password) || empty($nickname))) {

        $connection = mysql_connect ('localhost', 'zorik_if039', '9731')
        or die ('Unable to connect!');
        mysql_select_db('zorik_if039') or die (mysql_error());
        mysql_query("set character_set_client='utf8'"); 
        mysql_query("set character_set_server='utf8'"); 
        mysql_query("set character_set_results='utf8'"); 
        mysql_query("set collation_connection='utf8_unicode_ci'");

        $query = "SELECT * FROM user where email='$email'";
        $sql = mysql_query($query) or die(mysql_error());
        if (mysql_num_rows($sql) > 0) {
            $error = 1;
            $errormessage = 'User with this email is already registered';
        } else {
            $query2 = "SELECT * FROM user where nickname='$nickname'";
            $sql = mysql_query($query2) or die(mysql_error());
            if (mysql_num_rows($sql) > 0){
                $error = 1;
                $errormessage = $errormessage.' This nickname is in use';
            } else {
                $query3 = "INSERT INTO user (email, password, nickname )
                           VALUES ('$email', '$mdPassword', '$nickname')";
                $result = mysql_query($query3) or die(mysql_error());
                $query4 = "SELECT * FROM user where email='$email' and password='$mdPassword'";
                $result = mysql_query($query4) or die(mysql_error());;
                $row=mysql_fetch_array($result);
                $_SESSION['user_id']=$row['id'];
                $login['logged'] = true;
                $login['user_id'] = $row['id'];
            }
        }
    } else {
        $error = 1;
        $errormessage = 'Email, password or nickname is(are) empty';
    }
    $ajaxresult = (object) array('error' => $error, 'errormessage' => $errormessage, 'data' => $login);
    echo json_encode($ajaxresult);

?>